//
//  MenuViewController.m
//  项目三
//
//  Created by rimi1 on 2016/12/9.
//  Copyright © 2016年 Wangxingqian. All rights reserved.
//

#import "MenuViewController.h"
#import "DetailViewController.h"

#import "MenuListModel.h"
#import "MenuListTableViewCell.h"
#import "MenuCollection.h"// 弹框
#import "MenuHeadButton.h"// 头部分类视图
#import "NotView.h"

#import "NetRequest+Menu.h"

@interface MenuViewController () <UITableViewDelegate, UITableViewDataSource, MenuCollectionDelegate>

@property (nonatomic, strong) NSMutableArray *classArr;
@property (nonatomic, strong) NSMutableArray <MenuListModel *> *modelArr;
@property (nonatomic, copy) NSString *selectId;// 选中的分类id
@property (nonatomic, assign) NSInteger page;

@property (nonatomic, strong) MenuHeadButton *headButton;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) MenuCollection *collectionView;

@property (nonatomic, strong) NotView *notView;

@end

@implementation MenuViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initializeDataSource];
    [self initializeAppearance];
}

#pragma mark - initialize

- (void)initializeDataSource {
    self.classArr = [NSMutableArray array];
    self.modelArr = [NSMutableArray array];
    self.page = 1;
    [self urlMenuClassRequest];
}

- (void)initializeAppearance {
    [self.view addSubview:self.headButton];
    [self.view addSubview:self.tableView];
}

#pragma mark - URLRequest

- (void)urlMenuClassRequest {
    [NetRequest getMenuClassifyRequestSucceed:^(id response) {
        if ([response[@"status"] integerValue] == 1) {
            [self.notView removeFromSuperview];
            [self.classArr addObjectsFromArray:response[@"tngou"]];
            
            self.collectionView = [[MenuCollection alloc] initWithDataArr:self.classArr];
            self.collectionView.delegate = self;
            [self.headButton assignmentButtonWithArr:self.classArr];
            
            self.selectId = self.classArr[0][@"id"];
            [self urlMenuListRequest];
        }else {
            [self.view addSubview:self.notView];
            [Alert alertWithTitle:@"请求错误" message:nil];
        }
        
    } failure:^(NSError *error) {
        [self.view addSubview:self.notView];
        [Alert alertWithTitle:@"请求错误" message:nil];
    }];
}

- (void)urlMenuListRequest {
    NSDictionary *parameter = @{@"id":self.selectId, @"page":[NSString stringWithFormat:@"%ld", self.page], @"rows":@"10"};
    
    [NetRequest getMenuListRequestWithParameter:parameter succeed:^(id response) {
        if ([response[@"status"] integerValue] == 1) {
            NSArray *arr = response[@"tngou"];
            if (arr.count == 0) {
                [[RequestError sharedError] showErrorWithTitle:@"没有更多数据了"];
                [self.tableView.mj_footer endRefreshing];
                return;
            }
            
            [self.modelArr addObjectsFromArray:[MenuListModel modelArrForArray:arr]];
            
        }else {
            [Alert alertWithTitle:@"请求错误" message:nil];
        }
        
        [self.tableView.mj_footer endRefreshing];
        [self.tableView reloadData];
        if (self.page == 1 && self.modelArr.count != 0) {
            [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO];
        }
        
    } failure:^(NSError *error) {
        self.page--;
        [self.tableView.mj_footer endRefreshing];
        [self.tableView reloadData];
        [Alert alertWithTitle:@"请求错误" message:nil];
    }];
}

- (void)upPullLoad {
    self.page++;
    [self urlMenuListRequest];
}

#pragma mark - Custom Method

- (void)headButtonStatusWithButton:(UIButton *)sender {
    for (int i = 0; i < 4; i++) {
        UIButton *button = [self.headButton viewWithTag:100 + i];
        button.selected = NO;
    }
    
    sender.selected = YES;
}

- (void)refreshSelectIdWithIndex:(NSInteger)index {
    self.page = 1;
    self.selectId = self.classArr[index][@"id"];
    self.modelArr = [NSMutableArray array];
    [self urlMenuListRequest];
}

#pragma mark - respondsTo..
// 100 起
- (void)respondsToHeadButton:(UIButton *)sender {
    if (sender.tag == 103) {
        [self.collectionView showAnimation];
        return;
    }
    
    [self headButtonStatusWithButton:sender];
    NSInteger index = sender.tag - 100;
    [self refreshSelectIdWithIndex:index];
    [self.collectionView removeColor];
}

#pragma mark - MenuCollectionDelegate

- (void)menuCollection:(MenuCollection *)menuCollection selectOfIndexPath:(NSIndexPath *)indexPath {
    [self.collectionView hideAnimation];
    UIButton *button = [self.headButton viewWithTag:103];
    [self headButtonStatusWithButton:button];
    NSInteger index = indexPath.row + 3;
    [self refreshSelectIdWithIndex:index];
}

#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.modelArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *reusing = @"MenuListCell";
    MenuListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reusing];
    if (!cell) {
        cell = [[MenuListTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reusing];
    }
    MenuListModel *model = self.modelArr[indexPath.row];
    
    NSURL *url = [NSURL URLWithString:model.img];
    [cell.imageViewList sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"默认加载图"] options:SDWebImageProgressiveDownload];
    cell.name.text = model.name;
    cell.food.text = model.food;
    cell.backgroundColor = [UIColor clearColor];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
}

#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return WXQAdaptionHeight(115);
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    MenuListModel *model = self.modelArr[indexPath.row];
    DetailViewController *detail = [[DetailViewController alloc] init];
    detail.hidesBottomBarWhenPushed = YES;
    detail.menuId = model.menuId;
    [self.navigationController pushViewController:detail animated:YES];
}

#pragma mark - get

- (MenuHeadButton *)headButton {
    
    if (!_headButton) {
        
        _headButton = [[MenuHeadButton alloc] initWithFrame:CGRectMake(0, 0, kWIDTH, 35)];
        _headButton.backgroundColor = kCOLOR_RGB(253, 253, 253, 1);
        
        __weak MenuViewController *menu = self;
        _headButton.tapBlcok = ^(UIButton *button) {
            [menu respondsToHeadButton:button];
        };
        
    }
    return _headButton;
}

- (UITableView *)tableView {
    
    if (!_tableView) {
        
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.headButton.frame), kWIDTH, kHEIGHT - 64 - self.headButton.bounds.size.height - 49) style:UITableViewStylePlain];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.tableFooterView = [UIView new];
        _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(upPullLoad)];
        _tableView.backgroundColor = kCOLOR_RGB(236, 236, 236, 1);
        
    }
    return _tableView;
}

- (NotView *)notView {
    
    if (!_notView) {
        
        _notView = [[NotView alloc] initWithFrame:CGRectMake(0, 0, kWIDTH, kHEIGHT - 64 - 49)];
        _notView.backgroundColor = [UIColor whiteColor];
        _notView.title.text = @"请求出错...";
        
        __weak MenuViewController *menu = self;
        _notView.tapRefresh = ^() {
            [menu urlMenuClassRequest];
        };
        
    }
    return _notView;
}



@end











